<template>
  <el-scrollbar height="100vh">
    <div class="container">
      <el-affix :offset="1">
        <h1 class="title">制作第一个openlayers地图</h1>
      </el-affix>
      <div id="map" class="map-x"></div>
      <div class="codestyle"><Code /></div>
      <dl>
        <p class="dl-main-title">对于要渲染的地图，需要一个视图(view)、一个或多个图层(layers)以及一个目标容器(target)，即可初始化完成一个地图！</p>
        <dt>Map</dt>
        <dd>Map地图是 OpenLayers 的核心组件，可加载各类地图与功能控件，用于渲染、表现动态地图。</dd>
        <dt>target</dt>
        <dd>目标容器</dd>
        <dt>layers(图层)</dt>
        <dd>包含多个调用数据的子类，由子类的实例加载地图数据，必须结合图层数据源匹配使用。</dd>
        <dt>view(地图视图)</dt>
        <dd>控制地图缩放等基本交互，以及地图投影坐标系、地图中心点、分辨率、旋转角度等。</dd>
      </dl>
    </div>
  </el-scrollbar>
</template>
<script>
import Code from './code.vue'
import ol from 'ol'
import {
  onMounted,
  ref
} from 'vue'
import 'ol/ol.css'
import { Map, View } from 'ol'
import Tile from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ' // 引入XYZ地图格式
export default {
  name: 'FiretMap',
  setup () {
    const map = ref(null)
    onMounted(() => {
      init()
    })

    const init = () => {
      map.value = new Map({
        target: 'map', // 视图容器id
        layers: [
          new Tile({
            name: 'defaultLayer',
            source: new XYZ({
              url: 'http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}'
            })
          })
        ],
        view: new View({
          // 地图视图
          projection: 'EPSG:4326', // 坐标系，有EPSG:4326和EPSG:3857
          center: [116.41400, 39.91500], // 北京坐标
          minZoom: 1, // 地图缩放最小级别
          zoom: 12 // 地图缩放级别（打开页面时默认级别）
        })
      })
      createLine()
    }
    const createLine = () => {
      var points = [
        [-89.8802, 32.5804],
        [-95.04286, 46.9235]
      ]

      for (var i = 0; i < points.length; i++) {
        points[i] = ol.proj.transform(points[i], 'EPSG:4326', 'EPSG:3857')
      }

      var featureLine = new ol.Feature({
        geometry: new ol.geom.LineString(points)
      })

      var vectorLine = new ol.source.Vector({})
      vectorLine.addFeature(featureLine)

      var vectorLineLayer = new ol.layer.Vector({
        source: vectorLine,
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: '#00FF00',
            weight: 4
          }),
          stroke: new ol.style.Stroke({
            color: '#00FF00',
            width: 2
          })
        })
      })

      map.addLayer(vectorLineLayer)
    }
    return {
      map
    }
  },
  components: {
    Code
  }
}
</script>
<style lang="scss" scoped>
  @import '../../css/main.scss'
</style>
